package com.itheima.web.shiro;

import com.itheima.doamin.system.Module;
import com.itheima.doamin.system.User;
import com.itheima.service.system.ModuleService;
import com.itheima.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    ModuleService moduleService;
    /**
     * 此方法为授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获得认证成功的用户
        User user = (User)principals.fromRealm(this.getName()).iterator().next();
        //获得获得用户所有的模块
        List<Module> moduleByUserId = moduleService.getModuleByUserId(user);
        //创建set集合用于存入
        HashSet permission=new HashSet();
        //将模块名存入set集合中
        for (Module module:moduleByUserId){
            permission.add(module.getName());
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permission);
        return simpleAuthorizationInfo;
    }


    /**
     * 此方法为认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //取得表单中的账号和明文密码
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)token;
        String email = usernamePasswordToken.getUsername();
        //使用用户名到数据库进行查询
        User user = userService.toLogin(email);
        if (user!=null){
            //用户名正确
            SimpleAuthenticationInfo simpleAuthenticationInfo=
                    new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
